#!/bin/bash

function finish() {
	f="${1}"

	# No control fd: bail out
	[[ -z "${f}" || -z "${CYDIA}" ]] && return
	cydia=(${CYDIA})

	# Cydia control fd version != 1: bail out
	[[ ${cydia[1]} -eq 1 ]] || return

	echo "finish:${f}" >&${cydia[0]}
}

# Clear Inbox folder
if [ -d "/var/mobile/Library/Application Support/Containers/com.matchstic.reprovision.ios/Documents/Inbox" ]; then
    rm -rf "/var/mobile/Library/Application Support/Containers/com.matchstic.reprovision.ios/Documents/Inbox"
fi

# Handle the daemon
echo "(Re)-loading daemon..."
chown root /Library/LaunchDaemons/com.matchstic.reprovisiond.plist

# Unload for an upgrade. - Might spew an error, so hide that.
/bin/launchctl unload /Library/LaunchDaemons/com.matchstic.reprovisiond.plist 2>/dev/null || /sbin/launchctl unload /Library/LaunchDaemons/com.matchstic.reprovisiond.plist 2>/dev/null
/bin/launchctl load /Library/LaunchDaemons/com.matchstic.reprovisiond.plist 2> /dev/null || /sbin/launchctl load /Library/LaunchDaemons/com.matchstic.reprovisiond.plist

# Reload application cache
echo "Reloading application cache"
uicache

# Classic easter egg
echo "Do, or do not. There is no try."

# Finally, request Cydia to restart SpringBoard after installation.
# This is ensure we catch cases where users need to log in after install.
finish restart